<?php
namespace App\Api\Controllers\CmbcUnion;


use App\Api\Controllers\CmbcUnion\BaseController as base;
use App\Api\Controllers\Config\CmbcUnionPayConfigController;
use App\Api\Controllers\Config\CmbcUnoinPayConfigController;

use App\Common\PaySuccessAction;
use App\Common\RefundSuccessAction;
use App\Models\MerchantWalletDetail;
use App\Models\RefundOrder;
use App\Models\UserWalletDetail;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use function EasyWeChat\Kernel\Support\get_client_ip;

class LogicController extends base
{
    public function __construct()
    {

    }


    public function payParams ($data_insert, $data)
    {
        try {
            $store_id = $data['store_id'] ?? '';
            $store_pid = $data['store_pid'] ?? '';
            $merchant_id = $data['merchant_id'] ?? '';
            $total_amount = $data['total_amount'] ?? '';
            $ways_type = $data['ways_type'] ?? '';
            $store_name = $data['store_name'] ?? '';
            $config_id = $data['config_id'] ?? '';
            $ways_type_desc = $data['ways_type_desc'] ?? '';
            $ways_source = $data['ways_source'] ?? '';
            $title = $data['title'] ?? '';
            $tg_user_id = $data['tg_user_id'] ?? '';
            $out_trade_no = $data['out_trade_no'] ?? '';
            $code = $data['code'] ?? '';
            $company = $data['company'] ?? '';
            $ways_source_desc = $data['ways_source_desc'] ?? '';
            $device_id = $data['device_id'] ?? ''; //终端设备号.注:当中国银联时,为必填

            $payConfig = new CmbcUnionPayConfigController();
            $config = $payConfig->config($config_id);

            if (!$config) {
                return json_encode([
                    'status' => 2,
                    'message' => '民生联合收单支付配置不存在请检查配置'
                ]);
            }

            $merchant = $payConfig->merchant($store_id, $store_pid);
            if (!$merchant) {
                return json_encode([
                    'status' => 2,
                    'message' => '民生联合收单支付商户号不存在-4'
                ]);
            }

            //入库参数
            $data_insert['out_trade_no'] = $out_trade_no;
            $data_insert['ways_type'] = $ways_type;
            $data_insert['ways_type_desc'] = $ways_type_desc;
            $data_insert['ways_source'] = $ways_source;
            $data_insert['company'] = $company;
            $data_insert['ways_source_desc'] = $ways_source_desc;

            $insert_re =  (new \App\Api\Controllers\BaseController())->insert_day_order($data_insert);
            if (!$insert_re) {
                return json_encode([
                    'status' => 2,
                    'message' => '订单未入库'
                ]);
            }
            $paytype = '';
            if ($ways_source == 'weixin') {
                $paytype = '08';
            }
            if ($ways_source == 'alipay') {
                $paytype = '09';
            }
            if ($ways_source == 'unionpay') {
                $paytype = '12';
            }
            $terminal_info = ['deviceId' => $data['store_id'], 'deviceIp' => '127.0.0.1'];
            $payData = [
                'platform_id'  => $config->platform_id,
                'mch_id' => $merchant->mch_id,
                'paytype' => $paytype,
                'authcode' => $code,
                'out_trade_no' => $out_trade_no,
                'total_amount' => $total_amount,
                'terminal_info' => $terminal_info,
                'spbillcreateip' => get_client_ip()
            ];

            //单品
            $isGoods = 2;
            if (isset($data['store_id']) && !empty($data['store_id'])) {
                $isGoods =  \App\Models\Store::where('store_id', $data['store_id'])->value('is_goods');
            }

            if (isset($data['couponDetail']) && !empty($data['couponDetail']) && $isGoods == 1) {
                $goods = json_decode($data['couponDetail'], true);
                $goodsArr = [];
                foreach ($goods['goods_detail'] as $v) {
                    $price = $v['price'] * 0.01;
                    $goodsArr[] = [
                        'quantity'  => $v['quantity'],
                        'goodsId'   => $v['goods_id'],
                        'price'     => sprintf("%.2f", $price),
                        'goodsName' => $v['goods_name'],
                        'wxPayGoodsId' => $v['goods_id'],
                    ];
                }
                ksort($goodsArr);
                $costPrice = $goods['cost_price'] * 0.01;
                $costPrice = number_format($costPrice, 2, '.', '');
                $payData['goodsdetail'] = json_encode([
                    'costPrice'   => $costPrice,
                    'receiptId'   => $goods['receipt_id'],
                    'goodsDetail' => $goodsArr,
                ]);
            }

            $return = (new PayController())->scan_pay($payData);
            //返回支付成功
            if ($return['status'] == 1) {
                $trade_no = '';
                $pay_time = date('Y-m-d H:i:s', time());
                $buyer_pay_amount = $return['data']['body']['tranamt'];
                $remark = $return['data']['head']['tranflow'];
                $update_data = [
                    'trade_no' => $trade_no,
    //                'other_no' => $other_no,
                    'remark' => $remark,
                    'buyer_id' => '',
                    'status' => '1',
                    'pay_status_desc' => '支付成功',
                    'pay_status' => 1,
                    'payment_method' => '', //credit：信用卡 pcredit：花呗（仅支付宝） debit：借记卡 balance：余额 unknown：未知
                    'pay_time' => $pay_time,
                    'buyer_pay_amount' => $buyer_pay_amount //用户实际支付
                ];
                (new \App\Api\Controllers\BaseController())->update_day_order($update_data, $out_trade_no);

                //支付成功后的动作
                $data = [
                    'ways_type' => $data['ways_type'],
                    'ways_type_desc' => $data['ways_type_desc'],
                    'company' => $data_insert['company'],
                    'source_type' => $data['ways_type'], //返佣来源
                    'source_desc' => '民生', //返佣来源说明
                    'total_amount' => $total_amount,
                    'other_no' => $trade_no,
                    'out_trade_no' => $out_trade_no,
                    'rate' => $data_insert['rate'],
                    'fee_amount' => $data_insert['fee_amount'],
                    'merchant_id' => $merchant_id,
                    'store_id' => $store_id,
                    'user_id' => $tg_user_id,
                    'config_id' => $config_id,
                    'store_name' => $store_name,
                    'ways_source' => $data['ways_source'],
                    'pay_time' => $pay_time,
                    'device_id' => isset($data['device_id']) ? $data['device_id'] : "",
                ];
                PaySuccessAction::action($data);

                return json_encode([
                    'status' => 1,
                    'pay_status' => '1',
                    'message' => '支付成功',
                    'data' => [
                        'out_trade_no' => $out_trade_no,
                        'ways_type' => $ways_type,
                        'total_amount' => $total_amount,
                        'store_id' => $store_id,
                        'store_name' => $store_name,
                        'config_id' => $config_id,
                        'pay_time' => $pay_time,
                        'trade_no' => $trade_no,
                        'ways_source' => $data['ways_source'],
                    ]
                ]);
            } //支付中
            elseif ($return['status'] == 2) {
                return json_encode([
                    'status' => 1,
                    'pay_status' => 2,
                    'message' => '支付中',
                    'data' => [
                        'out_trade_no' => $out_trade_no,
                        'ways_type' => $ways_type,
                        'ways_source' => $data['ways_source'],
                        'total_amount' => $total_amount,
                        'store_id' => $store_id,
                        'store_name' => $store_name,
                        'config_id' => $config_id,
                    ]
                ]);
            }
            else {
                return json_encode([
                    'status' => 2,
                    'message' => $return['message']
                ]);
            }
        } catch (\Exception $ex) {
            return [
                'status' => 2,
                'message' => $ex->getMessage().' | '.$ex->getFile().' | '.$ex->getLine(),
            ];
        }
    }

    public function queryParams ($store_id, $store_pid, $data, $order)
    {
        try {
            $config_id = $data['config_id'] ?? '';

            $payConfig = new CmbcUnionPayConfigController();
            $config = $payConfig->config($config_id);
    
            if (!$config) {
                return json_encode([
                    'status' => 2,
                    'message' => '民生联合收单配置不存在请检查配置'
                ]);
            }
    
    
            $payData = [
                'platform_id'  => $config->platform_id,
                "tranflow" => $order->remark,
            ];
            $return = (new PayController())->order_query($payData, $order->out_trade_no);

            //返回支付成功
            if ($return['status'] == 1) {
                $trade_no = '';
                $pay_time = date('Y-m-d H:i:s', time());
                $buyer_pay_amount = $return['data']['body']['settleAmt'];
                if ($order->pay_status != 1) {
                    $update_data = [
                        'trade_no' => $trade_no,
    //                'other_no' => $other_no,
                        'buyer_id' => '',
                        'status' => '1',
                        'pay_status_desc' => '支付成功',
                        'pay_status' => 1,
                        'payment_method' => '', //credit：信用卡 pcredit：花呗（仅支付宝） debit：借记卡 balance：余额 unknown：未知
                        'pay_time' => $pay_time,
                        'buyer_pay_amount' => $buyer_pay_amount //用户实际支付
                    ];
                    (new \App\Api\Controllers\BaseController())->update_day_order($update_data, $order->out_trade_no);
    
                    //支付成功后的动作
                    $data = [
                        'ways_type' => $order->ways_type,
                        'ways_type_desc' => $order->ways_type_desc,
                        'company' => $order->company,
                        'source_type' => $order->ways_type, //返佣来源
                        'source_desc' => '民生', //返佣来源说明
                        'total_amount' => $order->total_amount,
                        'other_no' => $order->other_no,
                        'out_trade_no' => $order->out_trade_no,
                        'rate' => $order->rate,
                        'fee_amount' => $order->fee_amount,
                        'merchant_id' => $order->merchant_id,
                        'store_id' => $store_id,
                        'user_id' =>  $order->user_id,
                        'config_id' => $config_id,
                        'store_name' =>  $order->store_name,
                        'ways_source' =>  $order->ways_source,
                        'pay_time' => $pay_time,
                        'device_id' => isset($data['device_id']) ? $data['device_id'] : "",
                    ];
                    PaySuccessAction::action($data);
                }
                return json_encode([
                    'status' => 1,
                    'pay_status' => '1',
                    'message' => '支付成功',
                    'data' => [
                        'out_trade_no' => $order->out_trade_no,
                        'ways_type' => $order->ways_type,
                        'total_amount' => $order->total_amount,
                        'store_id' => $store_id,
                        'store_name' => $order->store_name,
                        'config_id' => $config_id,
                        'pay_time' => $pay_time,
                        'trade_no' => $trade_no,
                        'ways_source' => $order->ways_source,
                    ]
                ]);
            } //支付中
            elseif ($return['status'] == 2) {
                return json_encode([
                    'status' => 1,
                    'pay_status' => 2,
                    'message' => '支付中',
                    'data' => [
                        'out_trade_no' => $order->out_trade_no,
                        'ways_type' => $order->ways_type,
                        'ways_source' => $order->ways_source,
                        'total_amount' => $order->total_amount,
                        'store_id' => $store_id,
                        'store_name' => $order->store_name,
                        'config_id' => $config_id
                    ]
                ]);
            }
            else {
                return json_encode([
                    'status' => 3,
                    'pay_status' => 3,
                    'message' => $return['message'],
                    'data' => [
                        'out_trade_no' => $order->out_trade_no
                    ]
                ]);
            }
         } catch (\Exception $e) {
            return json_encode([
                'status' => -1,
                'message' => $e->getMessage().' | '.$e->getFile().' | '.$e->getLine()
            ]);
        }
    }

    public function refundParams($data, $order)
    {
        $config_id = $data['config_id'] ?? '';
        $device_id = $data['device_id'] ?? ''; //终端设备号.注:当中国银联时,为必填

        $payConfig = new CmbcUnionPayConfigController();
        $config = $payConfig->config($config_id);

        if (!$config) {
            return json_encode([
                'status' => 2,
                'message' => '民生银行支付配置不存在请检查配置'
            ]);
        }

        $merchant = $payConfig->merchant($data['store_id'], $data['store_pid']);
        if (!$merchant) {
            return json_encode([
                'status' => 2,
                'message' => '民生银行支付商户号不存在'
            ]);
        }
        $count = RefundOrder::where(['out_trade_no' => $data['out_trade_no']])->count();

        $remark = DB::table("orders")->where('out_trade_no', $order->out_trade_no)->value('remark');
        $payData = [
            'platform_id'  => $config->platform_id,
            "mch_id" => $merchant->mch_id,
            "out_trade_no" => $remark,
            "refund_amount" => $data['refund_amount'],
            "refund_no" => $data['refund_no'].$count
        ];
        $return = (new PayController())->refund($payData);
        //退款请求成功
        if ($return['status'] == '1') {
            $insert_data = [
                'status' => '6',
                'pay_status' => 6,
                'pay_status_desc' => '已退款',
                'refund_amount' => $data['new_refund_amount'],
                'fee_amount' => $data['new_fee_amount']
            ];
            (new \App\Api\Controllers\BaseController())->update_day_order($insert_data, $data['out_trade_no']);

            RefundOrder::create([
                'ways_source' => $order->ways_source,
                'type' => $data['ways_type'],
                'refund_amount' => $data['refund_amount'], //退款金额
                'refund_no' => $payData['refund_no'], //平台退款单号
                'store_id' => $data['store_id'],
                'merchant_id' => $data['merchant_id'],
                'out_trade_no' => $data['out_trade_no'],
                'trade_no' => $order->trade_no
            ]);
            //退款成功后的操作
            RefundSuccessAction::action([
                'out_trade_no'=>$data['out_trade_no'],
                'refund_no' => $payData['refund_no'], //平台退款单号
            ]);

            //返佣去掉
            UserWalletDetail::where('out_trade_no', $data['out_trade_no'])->update([
                'settlement' => '03',
                'settlement_desc' => '退款订单'
            ]);
            MerchantWalletDetail::where('out_trade_no', $data['out_trade_no'])->update([
                'settlement' => '03',
                'settlement_desc' => '退款订单'
            ]);

            $data = [
                'refund_amount' => $data['refund_amount'],
                'out_trade_no' => $data['out_trade_no'],
                'refund_no' => $payData['refund_no'], //平台退款单号
                'other_no' => $order->trade_no
            ];
            return json_encode([
                'status' => '1',
                'message' => '退款成功',
                'data' => $data
            ]);
        } else {
            //其他情况
            $message = $return['message'];
            return json_encode([
                'status' => '2',
                'message' => $message
            ]);
        }
    }

    public function qrSubmitParams ($data_insert, $data)
    {
        $payConfig = new \App\Api\Controllers\Config\CmbcUnionPayConfigController();
        $config = $payConfig->config($data['config_id']);
        if (!$config) {
            return json_encode([
                'status' => 2,
                'message' => '民生联合支付配置不存在请检查配置'
            ]);
        }
        $merchant = $payConfig->merchant($data['store_id'], $data['store_pid']);
        if (!$merchant) {
            return json_encode([
                'status' => 2,
                'message' => '民生联合支付商户号不存在'
            ]);
        }
        //支付宝
        if ($data['ways_type'] == '70002') {
            $selectTradeType = '06';
            $out_trade_no = 'ali_qr' . date('YmdHis', time()) . substr(microtime(), 2, 6) . sprintf('%03d', rand(0, 999));
            //入库参数
            $data_insert['ways_type'] = $data['ways_type'];
            $data_insert['ways_type_desc'] = '支付宝';
            $data_insert['ways_source'] = 'alipay';
            $data_insert['ways_source_desc'] = '支付宝';
            $data_insert['out_trade_no'] = $out_trade_no;
        }
        //云闪付
        if ($data['ways_type'] == '70003') {
            $selectTradeType = '12';
            $out_trade_no = 'un_qr' . date('YmdHis', time()) . substr(microtime(), 2, 6) . sprintf('%03d', rand(0, 999));
            //入库参数
            $data_insert['ways_type'] = $data['ways_type'];
            $data_insert['ways_type_desc'] = '银联支付';
            $data_insert['ways_source'] = 'unionpay';
            $data_insert['ways_source_desc'] = '银联支付';
            $data_insert['out_trade_no'] = $out_trade_no;
        }
        //微信
        if ($data['ways_type'] == '70001') {
            $selectTradeType = '05';
            $out_trade_no = 'wx_qr' . date('YmdHis', time()) . substr(microtime(), 2, 6) . sprintf('%03d', rand(0, 999));
            //入库参数
            $data_insert['ways_type'] = $data['ways_type'];
            $data_insert['ways_type_desc'] = '微信支付';
            $data_insert['ways_source'] = 'weixin';
            $data_insert['ways_source_desc'] = '微信支付';
            $data_insert['out_trade_no'] = $out_trade_no;
        }
        $payData = [
            'mch_id'       => $merchant->mch_id,
            'platform_id'  => $config->platform_id,
            'paytype'      => $selectTradeType,
            'total_amount' => $data['total_amount'],
            'out_trade_no' => $out_trade_no,
            'openid'       => $data['open_id'],
            'goods_detail' => '{"productlist":[{"productname":"qr","productnum":"1","productamt":"'.$data['total_amount'].'"}]}'
        ];

        $return = (new PayController())->qr_submit($payData);
        if ($return['status'] == 1) {
            $insert_re = (new \App\Api\Controllers\BaseController())->insert_day_order($data_insert);
            if (!$insert_re) {
                return json_encode([
                    'status' => 2,
                    'message' => '订单未入库'
                ]);
            }
            return json_encode([
                'status' => 1,
                'data' => $return['data']
            ]);
        } else {
            return json_encode([
                'status' => 2,
                'message' => $return['message']
            ]);
        }
    }

    //终端报备
    public function device ($info)
    {
        $base = base::getInstance();
        $chltype = 'WEIXIN';
        $payConfig = new CmbcUnionPayConfigController();
        $config = $payConfig->config($info['store']['config_id']);
        $merchant = $payConfig->merchant($info['store']['store_id'], $info['store']['pid']);
        $head = [
            'platmerid' => $config->platform_id,
            'trancode'  => 'CMS036',
            'tranflow'  => $config->platform_id.'-'.uniqid(),
        ];
        $data = [
            'merid' => $merchant->mch_id,
            'chltype' => $chltype,
            'operationId' => '00',
            'deviceId' => $info['store']['store_id'],
            'deviceType' => '11',
            'deviceAddress' => $info['store']['store_address'],
            'provinceCode' => $info['store']['province_code'],
            'cityCode' => $info['store']['city_code'],
            'districtCode' => $info['store']['area_code'],
            'trmDevcMdl' => 'pos01',
        ];
        Log::channel('cmbcunion')->info('民生联合收单报备1-'.json_encode([$head, $data]));
        $ret[]  = json_decode($base->params($data, $head)->build($base::APPLY), true);
        $data['chltype'] = 'ALI';
        $head['tranflow'] = $config->platform_id.'-'.uniqid();
        Log::channel('cmbcunion')->info('民生联合收单报备2-'.json_encode([$head, $data]));
        $ret[]  = json_decode($base->params($data, $head)->build($base::APPLY), true);

        Log::channel('cmbcunion')->info('民生联合收单-'.json_encode($ret));

        $msg = [];
        foreach ($ret as $k => $v) {
            if ($v['message']['data']['head']['respcode'] != 'C000000000') {
                $msg[] = $k.'---'.$v['message']['data']['head']['respmsg'];
            }
        }
        if ($msg) {
            return [
                'status' => 2,
                'message' => $msg,
            ];
        } else {
            return [
                'status' => 1,
                'message' => '成功',
            ];
        }
    }
    public function apply ($data)
    {


       if ($_GET['opt'] == 'apply') {
           $address = [
               'provinceCode' => $data['store']['province_code'],
               'cityCode' => $data['store']['city_code'],
               'districtCode' => $data['store']['area_code'],
               'address' => $data['store']['store_address'],
           ];
           $merinfos =  [];
           $info = [
               'customertype' => $data['store']['store_type'], //1：个体工商户2：企业商户3：小微商户
               'corname' => $data['store']['store_name'], //企业、小微商户结算卡只能绑定该名称下的银行卡，请谨慎填写。[客户类型]为[小微商户]时,请填写自然人姓名
               'shortname' => $data['store']['store_short_name'], //商户简称
               'managementaddress' => $address, //经营地址
           ];
           if ($data['store']['store_type'] == 3) {//3：小微商户
               //responsiblecertype		负责人证件类型	String	2	是		详见附件证件类型，身份证、港澳居民来往内地通行证、台湾居民来往大陆通行证、外国公民护照
               //responsibleid			    负责人证件号	String	22	是
               //responsibleidaddr		    负责人地址	String	10-120	是		证件类型”身份证”：输入身份证上的地址；证件类型非身份证：输入负责人在大陆地区的联系地址；
               //responsibleidbegin		负责人证件有效期开始日期	String	8	是		“证件有效期开始日期”小于等于当前入网日期。
               //responsibleidvalid		负责人证件有效期截止日期	String	8	是		长期: 9999/12/31”负责人证件有效期截止日期”大于等于当前入网日期； “负责人证件有效期截止日期”大于”受益所有人证件有效期开始日期”。
               //responsibleidfrontphoto	负责人证件正面照	String	128	是
               //responsibleidbackphoto	负责人证件反面照	String	128	是
               //proofphoto				租赁协议/产权证明/集中经营场所证明照（影像）	String	128	是
               //responsibleholdingphoto	负责人于经营场所手持营业执照/身份证件照片	String	128	是
               $merinfos = [
                   'responsiblecertype' => '03',
                   'responsibleid' => $data['store']['head_sfz_no'],
                   'responsibleidaddr' => $data['store']['store_address'],
                   'responsibleidbegin' => $this->dateFormat($data['store']['head_sfz_stime']),
                   'responsibleidvalid' => $this->dateFormat($data['store']['head_sfz_time']),
                   'responsibleidfrontphoto' => $this->imageUpload($data['img']['head_sfz_img_a']),
                   'responsibleidbackphoto' => $this->imageUpload($data['img']['head_sfz_img_b']),
                   'proofphoto' => $this->imageUpload($data['img']['store_img_b']),
                   'responsibleholdingphoto' => $this->imageUpload($data['img']['head_sfz_img_a']),
               ];
           }
           if ($data['store']['store_type'] == 1) {//1：个体工商户

               //businesslicenseno		营业执照号	String	20	是
               //businesslicensephoto	营业执照照片	String	128	是		1、企业商户、个体工商户上送；2、注册时可不上送，需按风控要求时效内补交。
               //managername				经营者姓名	String	32	是		个体商户结算卡只能绑定该姓名下的银行卡，请谨慎填写
               //managercertype			经营者证件类型	String	2	是		身份证、港澳居民来往内地通行证、台湾居民来往大陆通行证、外国公民护照.枚举信息
               //managerid				经营者证件号码	String	22	是
               //manageraddr				经营者地址	String	10-120	是		证件类型”身份证”：输入身份证上的地址；证件类型非身份证：输入经营折在大陆地区的联系地址；
               //manageridvalidbegin		经营者证件有效期开始日期	String	8	是		格式：yyyymmdd校验”证件有效期开始日期”小于等于当前入网日期。
               //manageridvalid			经营者身份证有效期		8	是		长期: 99991231格式：yyyymmdd”经营者证件有效期截止日期”大于等于当前入网日期；”经营者证件有效期截止日期”大于”经营者证件有效期开始日期”。
               //manageridphoto			经营者证件正面照	String	128	是
               //manageridbackphoto		经营者证件反面照	String	128	是
               $merinfos = [
                   'businesslicenseno' => $data['store']['store_license_no'],
                   'businesslicensephoto' => $this->imageUpload($data['img']['store_license_img']),//test9 store_license_img
                   'managername' => $data['store']['people'],
                   'managercertype' => '03',
                   'managerid' => $data['store']['head_sfz_no'],
                   'manageraddr' => $data['store']['store_address'],
                   'manageridvalidbegin' => $this->dateFormat($data['store']['head_sfz_stime']),
                   'manageridvalid' => $this->dateFormat($data['store']['head_sfz_time']),
                   'manageridphoto' => $this->imageUpload($data['img']['head_sfz_img_a']),
                   'manageridbackphoto' => $this->imageUpload($data['img']['head_sfz_img_b']),
               ];
               $info['phone'] = $data['store']['people_phone'];
           }

           if ($data['store']['store_type'] == 2) {//2：企业商户

               //businesslicensetype		证件类型	String	3	是	默认值101	101：营业执照X：其他
               //businesslicenseno		证件号码	String	20	是		企业商户必填
               //businesslicensephoto	证件照	String	128	否		1、企业商户、个体工商户上送；2、注册时可不上送，需按风控要求时效内补交。
               //operatorname			经办人姓名	String	16	是
               //operatoreidtype			经办人证件类型	String	2	是		身份证、港澳居民来往内地通行证、台湾居民来往大陆通行证、外国公民护照
               //operatoreid				经办人证件号码	String	22	是
               //operatoreaddr			经办人地址			否		证件类型”身份证”：输入身份证上的地址；证件类型非身份证：输入经办人在中国大陆地区的联系地址；
               //operatoreidvalidbegin	经办人证件有效期开始日期	String	8	是		格式：yyyymmdd”经办人证件有效期开始日期”小于等于当前入网日期。
               //operatoreidvalid		经办人证件有效期截止日期	String	8	是		格式：yyyymmdd”经办人证件有效期截止日期”大于等于当前入网日期； “经办人证件有效期截止日期”大于”经办人证件有效期开始日期”。
               //operatormobile			经办人手机号	String	13	是
               //operatoreidfrontphoto	经办人证件正面照	String	128	是		1、企业商户上送
               //operatoreidbackphoto	经办人证件反面照	String	128	是		1、企业商户上送
               //legalname				法定代表人姓名	String	32	是
               //legalidtype				法定代表人证件类型	String	2	是		身份证、港澳居民来往内地通行证、台湾居民来往大陆通行证、外国公民护照
               //legalid					法定代表人证件号码	String	22	是
               //legalidvalidbegin		法定代表人证件有效期开始日期	String	8	是		法定代表人证件有效期开始日期”小于等于当前入网日期。
               //legalidvalid			法定代表人证件有效期截止日期	String	8	是		长期: 99991231”法定代表人证件有效期截止日期”大于等于当前入网日期； “法定代表人证件有效期截止日期”大于”法定代表人证件有效期开始日期”。
               //legalidfrontphoto		法定代表人证件正面照	String	128	是		1、企业商户上送
               //legalidbackphoto		法人身份证背面照	String	128	是		1、企业商户上送
               //controllerinfos			受益所有人信息	Json	1000	是		见下方”受益所有人示例”
               //controlleridphotozip	受益所有人证件影像压缩文件	String	128	是		仅支持压缩文件
               //openingnophoto			银行账户开户证明文件	String	128	是		具体开户证明文件可登录“中投科信支付”公众号-常见问题中查阅
               $merinfos = [
                   'businesslicensetype' =>  '101',
                   'businesslicenseno' =>  $data['store']['store_license_no'],
                   'businesslicensephoto' =>  $this->imageUpload($data['img']['store_license_img']),
                   'operatorname' =>  $data['store']['people'],
                   'operatoreidtype' =>  '03',
                   'operatoreid' =>  $data['store']['head_sfz_no'],
                   'operatoreaddr' =>  $data['store']['store_address'],
                   'operatoreidvalidbegin' =>  $this->dateFormat($data['store']['head_sfz_time']),
                   'operatoreidvalid' =>  $this->dateFormat($data['store']['head_sfz_stime']),
                   'operatormobile' =>  $data['store']['people_phone'],
                   'operatoreidfrontphoto' =>  $this->imageUpload($data['img']['head_sfz_img_a']),
                   'operatoreidbackphoto' =>  $this->imageUpload($data['img']['head_sfz_img_b']),
                   'legalname' =>  $data['store']['people'],
                   'legalidtype' =>  '03',
                   'legalid' =>  $data['store']['head_sfz_no'],
                   'legalidvalidbegin' =>  $this->dateFormat($data['store']['head_sfz_stime']),
                   'legalidvalid' =>  $this->dateFormat($data['store']['head_sfz_time']),
                   'legalidfrontphoto' =>  $this->imageUpload($data['img']['head_sfz_img_a']),
                   'legalidbackphoto' =>  $this->imageUpload($data['img']['head_sfz_img_b']),
                   'controllerinfos' =>  '',
                   'controlleridphotozip' =>  '',
                   'openingnophoto' =>  '',
               ];
           }
           $merinfos['storephoto'] = $this->imageUpload($data['img']['store_logo_img']); //门头照
           $merinfos['storeinsidephoto'] = $this->imageUpload($data['img']['store_img_b']); //内部经营照

           $info['merinfos'] = $merinfos;
           echo json_encode($info);
           $base = base::getInstance();
           $info['platformId'] = 'CF3000053368';
           $ret  = json_decode($base->params($info, 'CMS013')->build($base::APPLY), true);
           if (isset($ret['data']['body']) && !empty($ret['data']['body'])) {
               $mch_id = $ret['data']['body']['merid'];
               $status = $ret['data']['body']['status'];
           }
       } else if ($_GET['opt'] == 'bind') { //绑卡

//            merid	中投商户号	String	12	是
//            accountno	账户号码	String	32	是
//            accounttype	账户类型	String	2	是	见附录 00	对私 01	对公
//            accountname	账户名称	String	30	是		个体：需与经营者姓名一致企业、小微：需与商户名称一致
//            bankname	银行名称	String	128	否		对公账户必输
//            bankcode	银行代码	String	8	否		对公账户必输，详情
//            bankpro	开户行所在省	String	20	否		对公账户必输，不带”省”或”自治区”，如湖南，北京，内蒙古等
//            bankcity	开户行所在市	String	30	否		对公账户必输，不带”市”字如北京
//            prebankmobile	银行预留手机号	String	13	否		对私四要素的绑卡验证用户上送手机号是否为银行预留手机号


           if ($data['store']['store_type'] == 2) {//2：企业商户
               $operatorname = $data['store']['store_name'];
           }
           if ($data['store']['store_type'] == 1) {//2：个体
               $operatorname = $data['store']['store_name'];
           }
           if ($data['store']['store_type'] == 3) {//2：小微
               $operatorname = $data['store']['store_name'];
           }


           $info = [
               'merid' =>  '101',
               'accountno' =>  $data['bank']->store_bank_no,
               'operatorname' => $operatorname
           ];
           if ($data['bank']->store_bank_type == "02") {
                $info['accounttype'] = '01';
                $info['bankname'] = $data['bank']->bank_name;
                $info['bankcode'] = $data['bank']->bank_no;
                $info['bankpro'] = $data['bank']->store_bank_type;
                $info['bankcity'] = $data['bank']->store_bank_type;
                $info['prebankmobile'] = $data['bank']->reserved_mobile;
           }else{
                $info['accounttype'] = '00';
           }


       } else if ($_GET['opt'] == 'sign') { //签约


       } else if ($_GET['opt'] == 'change_sign') { //换绑

       } else if ($_GET['opt'] == 'open_pay') { //条码支付开通

       }



    }

    public function cleanBase64($data) {
        $data = trim($data); // 移除前后的空白符
        return preg_replace('/[^A-Za-z0-9\+\/\=]/', '', $data); // 移除非法字符
    }

    public function dateFormat ($time)
    {
        return date('Ymd',strtotime($time));
    }

    public function imageUpload ($img)
    {
        $base = base::getInstance();

        // 读取图片文件内容
        $imageData = file_get_contents($img);
        // 将图片内容转换为Base64编码
        $base64Image = base64_encode($imageData);

        $base64Image = str_replace('/', '%2F', $base64Image);

        // 确保字符串长度大于50，否则返回原字符串或相应长度的字符串
        $last50 = substr($base64Image, -50);

        $data = [
            'imgs' => $base64Image,
            'last50' => $last50,
            'platformId' => 'CF3000053368'
        ];
        $ret  = json_decode($base->uploadImg($data, 'CMS003')->build($base::UPLOAD_IMG), true);

        if (isset($ret['data']) && !empty($ret['data'])) {
            $info = json_decode($ret['data'], true);
            if (isset($info['pictureid']) && !empty($info['pictureid'])) {
                return $info['pictureid'];
            }
        }
        return '';
    }

    public function getQuota(Request $request)
    {
        try {
            $ids = explode(',', $request->get('mch_id'));
            $base = base::getInstance();
            $payConfig = new \App\Api\Controllers\Config\CmbcUnionPayConfigController();
            $config = $payConfig->config(1234);
            if (!$config) {
                return json_encode([
                    'status' => 2,
                    'message' => '民生联合支付配置不存在请检查配置'
                ]);
            }
            $t = [];
            $companyRuleId = DB::table('company_rule')->where(['code' => 'cmbcunion'])->value('id');
            foreach ($ids as $v) {
                $head = [
                    'platmerid' => $config->platform_id,
                    'trancode'  => 'CMS034',
                    'tranflow'  => $config->platform_id.'-'.uniqid(),
                ];
                $body = [
                    'merid' => $v,
                    'activityCode' => $request->get('act_code'),
                ];
                $ret = json_decode($this->params($body, $head)->build($base::APPLY), true);
                if (isset($ret['message']['data']['head']['respcode']) && !empty($ret['message']['data']['head']['respcode'])
                    && $ret['message']['data']['head']['respcode'] == 'C000000000' && isset($ret['message']['data']['body']['coupons'])
                ) {
                    foreach ($ret['message']['data']['body']['coupons'] as $vv) {
                        $startDate = date('Ymd', strtotime($vv['startTime']));
                        $endDate = date('Ymd', strtotime($vv['endTime']));
                        $tmp = [
                            'company_rule_id' => $companyRuleId,
                            'company_code' => 'cmbcunion',
                            'mch_id' => $v,
                            'start_date' => $startDate,
                            'end_date' => $endDate,
                        ];
                        $t[] = array_merge($tmp, ['quota'  => $vv['balanceAmt']]);
                    }
                }else {
                    $message = '失败了';
                    if (isset($ret['message']['data']['head']['respmsg'])) {
                        $message = $ret['message']['data']['head']['respmsg'];
                    }
                    return [
                        'status' => 3,
                        'message' => $message,
                    ];
                }
            }

            if ($t) {
                return json_encode(['status' => 1, 'message' => '获取成功', 'data' => $t]);
            } else {
                return json_encode(['status' => 0, 'message' => '获取失败']);
            }
        } catch (\Exception $exception) {
            return json_encode(['status' => -1, 'message' => $exception->getMessage()]);
        }
    }





}
